//
//  HomeCourseView.m
//  fp
//
//  Created by xingshuai on 2020/11/15.
//

#import "HomeCourseView.h"

#import "XHPageControl.h"
#import "MyButton.h"

@interface HomeCourseView () <UIGestureRecognizerDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) UILabel *topLabel;
@property (nonatomic, strong) UIImageView *topImg;
@property (nonatomic, strong) UIImageView *contImg;
@property (nonatomic, strong) UIScrollView *scrolView;
@property (nonatomic, strong) XHPageControl *pageControl;

@end

@implementation HomeCourseView

-(UILabel *)topLabel {
    if (!_topLabel) {
        _topLabel = [[UILabel alloc]init];
        _topLabel.text = @"选择您想学习的科目";
        _topLabel.textColor = [UIColor colorWithHexString:@"#4E75FF"];
        _topLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleMedium size:18];
    }
    return _topLabel;
}

-(UIImageView *)topImg {
    if (!_topImg) {
        _topImg = [[UIImageView alloc]init];
        _topImg.userInteractionEnabled = YES;
        _topImg.image = [UIImage imageNamed:@"cource_top"];
        _topImg.backgroundColor = [UIColor clearColor];
    }
    return _topImg;
}

-(UIImageView *)contImg {
    if (!_contImg) {
        _contImg = [[UIImageView alloc]init];
        _contImg.userInteractionEnabled = YES;
        _contImg.image = [UIImage imageNamed:@"cource_cont"];
        _contImg.backgroundColor = [UIColor clearColor];
    }
    return _contImg;
}

-(UIScrollView *)scrolView {
    if (!_scrolView) {
        _scrolView = [[UIScrollView alloc]initWithFrame:CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width, self.bounds.size.height - 20)];
        _scrolView.pagingEnabled = YES;
        _scrolView.delegate = self;
        _scrolView.bounces = NO;
        _scrolView.showsHorizontalScrollIndicator = NO;
    }
    return _scrolView;
}

-(XHPageControl *)pageControl {
    if (!_pageControl) {
        //创建pageControl
        _pageControl = [[XHPageControl alloc] initWithFrame:CGRectMake(0, 0, 540, 20)];
        //设置点的总个数
        //_pageControl.numberOfPages = 7;
        //设置非选中点的宽度是高度的倍数(设置长条形状)
        _pageControl.otherMultiple = 7.5;
        //设置选中点的宽度是高度的倍数(设置长条形状)
        _pageControl.currentMultiple = 7.5;
        _pageControl.controlSpacing = 0;
        //设置样式.默认居中显示
        _pageControl.type = PageControlMiddle;
        //非选中点的颜色
        _pageControl.otherColor = [UIColor colorWithHexString:@"#F3F3F3"];
        //选中点的颜色
        _pageControl.currentColor = [UIColor colorWithHexString:@"#8EB3FF"];
        //代理
        //_pageControl.delegate = self;
        _pageControl.enabled = NO;
    }
    return _pageControl;
}

-(instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.5];
        
        [self addSubview:self.topImg];
        [self.topImg addSubview:self.topLabel];
        
        [self addSubview:self.contImg];
        [self.contImg addSubview:self.scrolView];
        
        [self.contImg addSubview:self.pageControl];
        
        UITapGestureRecognizer *tapp = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickGradeView)];
        tapp.delegate = self;
        [self addGestureRecognizer:tapp];
    }
    return self;
}

-(void)layoutSubviews {
    [super layoutSubviews];
    
    [self.contImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.mas_offset(540);
        make.height.mas_equalTo(self.contImg.mas_width).dividedBy(1.7);
    }];
    
    [self.topImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.contImg.mas_top);
        make.left.equalTo(self.contImg.mas_left);
        make.width.mas_equalTo(self.contImg.mas_width).dividedBy(1.95);
        make.height.mas_equalTo(self.topImg.mas_width).dividedBy(5.6);
    }];

    [self.topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.topImg);
        make.left.equalTo(self.topImg).offset(15);
        make.right.equalTo(self.topImg).offset(-15);
        make.top.bottom.equalTo(self.topImg);
    }];
    
    [self.scrolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.contImg);
        make.bottom.equalTo(self.contImg.mas_bottom).offset(-10);
    }];
    
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.contImg);
        make.bottom.equalTo(self.contImg.mas_bottom).offset(-20);
        make.left.right.equalTo(self.contImg);
        make.height.mas_offset(10);
    }];

}
-(void)setTotalList:(NSArray *)totalList {
    _totalList = totalList;
    NSInteger totalNum = totalList.count;
    NSInteger curNum = 0;
    if (totalNum % 8 != 0) {
        curNum = totalNum/8+1;
    } else if (totalNum < 8) {
        curNum = totalNum = 1;
    } else {
        curNum = totalNum/8;
    }
    NSInteger btnTag = 0;
    // 数组拆分（8个一组）
    NSArray *list = [self splitArray:totalList withSubSize:8];
    // scrollview滑动区域
    _scrolView.contentSize = CGSizeMake(540*curNum , 540/1.7-10);
    self.pageControl.numberOfPages = curNum;
    for (int i = 0; i < list.count; i ++) {
        UIView *btnView = [[UIView alloc]initWithFrame:CGRectMake(540*i+10, 10, 540-20, 540/1.7-20)];
        [self.scrolView addSubview:btnView];
        
        for (int j = 0; j < [[list objectAtIndex:i] count]; j ++) {
            MyButton *button = [[MyButton alloc]init];
            [button reloadBtnImg:@"def_img" btnText:[[list objectAtIndex:i] objectAtIndex:j]];
            if (j > 3) {
                button.frame = CGRectMake(520/4*(j-4)+5, 540/1.7/2-9, 540/4-10, 540/1.7/2-20);
            } else {
                button.frame = CGRectMake(520/4*j+5, 5, 540/4-10, 540/1.7/2-20);
            }
            button.tag = btnTag;
            [button addTarget:self action:@selector(clickBtnSubject:) forControlEvents:UIControlEventTouchUpInside];
            [btnView addSubview:button];
            btnTag ++;
        }
        
    }
}

/**
 * 将数组拆分成固定长度的子数组
 * @param array 需要拆分的数组
 * @param subSize 指定长度
 */
- (NSArray *)splitArray: (NSArray *)array withSubSize : (int)subSize{
//  数组将被拆分成指定长度数组的个数
  unsigned long count = array.count % subSize == 0 ? (array.count / subSize) : (array.count / subSize + 1);
//  用来保存指定长度数组的可变数组对象
  NSMutableArray *arr = [[NSMutableArray alloc] init];
  
//利用总个数进行循环，将指定长度的元素加入数组
  for (int i = 0; i < count; i ++) {
    //数组下标
    int index = i * subSize;
    //保存拆分的固定长度的数组元素的可变数组
    NSMutableArray *arr1 = [[NSMutableArray alloc] init];
    //移除子数组的所有元素
    [arr1 removeAllObjects];
    
    int j = index;
    //将数组下标乘以1、2、3，得到拆分时数组的最大下标值，但最大不能超过数组的总大小
    while (j < subSize*(i + 1) && j < array.count) {
      [arr1 addObject:[array objectAtIndex:j]];
      j += 1;
    }
    //将子数组添加到保存子数组的数组中
    [arr addObject:[arr1 copy]];
  }
  
  return [arr copy];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    NSInteger currentPage = targetContentOffset->x / 540;
    self.pageControl.currentPage = currentPage;
}

// 点击空白隐藏
-(void)clickGradeView {
    self.hidden = YES;
}

// 点击手势响应者
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isDescendantOfView:self.topImg] || [touch.view isDescendantOfView:self.contImg]) {
        return NO;
    }
    return YES;
}

// 当前点击的基础课程学科
-(void)clickBtnSubject:(UIButton *)sender {
    NSString *str = [self.totalList objectAtIndex:sender.tag];
    NSLog(@"学科 = %@",str);
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
